'use strict';

/* Controllers */

angular.module('myApp.controllers', []).
  controller('IndexCtrl', ['$scope','$http','$fileUploader',function($scope,$http,$fileUploader) {
//      // Creates a uploader
//      var uploader = $scope.uploader = $fileUploader.create({
//        scope: $scope,
//        url: '/upload',
//        autoUpload:true
//      });
//      uploader.filters.push(function(item /*{File|HTMLInputElement}*/) {
//        var type = uploader.isHTML5 ? item.type : '/' + item.value.slice(item.value.lastIndexOf('.') + 1);
//        type = '|' + type.toLowerCase().slice(type.lastIndexOf('/') + 1) + '|';
//        return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
//      });
//      // REGISTER HANDLERS
//
//      uploader.bind('afteraddingfile', function (event, item) {
//        console.info('After adding a file', item);
//      });
//
//      uploader.bind('afteraddingall', function (event, items) {
//        console.info('After adding all files', items);
//      });
//
//      uploader.bind('beforeupload', function (event, item) {
//        console.info('Before upload', item);
//      });
//
//      uploader.bind('progress', function (event, item, progress) {
//        console.info('Progress: ' + progress, item);
//      });
//
//      uploader.bind('success', function (event, xhr, item, response) {
//        console.info('Success', xhr, item, response);
//        response.name;
//      });
//
//      uploader.bind('cancel', function (event, xhr, item) {
//        console.info('Cancel', xhr, item);
//      });
//
//      uploader.bind('error', function (event, xhr, item, response) {
//        console.info('Error', xhr, item, response);
//      });
//
//      uploader.bind('complete', function (event, xhr, item, response) {
//        console.info('Complete', xhr, item, response);
//      });
//
//      uploader.bind('progressall', function (event, progress) {
//        console.info('Total progress: ' + progress);
//      });
//
//      uploader.bind('completeall', function (event, items) {
//        console.info('Complete all', items);
//      });
      var now = new Date();
      var report = $scope.report={
      title:'单击修改报告标题',
      date:''+now.getFullYear()+'.'+(now.getMonth()+1) + '.' + now.getDate(),
      content:[
//        {
//          type:'sub-title',
//          data:'一、总结报告'
//        },
//        {
//          type:'text',
//          data:'我的理想路线被突然截断了！但我已经考虑到这种可能性了（或者说至少有些明智的施工人员想到了），我继续向走廊尽头的楼梯口走去。因为我住在第10层，走路当然比搭电梯慢了，但最终我还是走到底层，最后从公寓的后门出来了。我又想到：我得折回去咖啡厅，所以我绕着公寓走到正对面的街道。瞧！我又回到理想路线上了，最终成功抵达目的地。      \n    这就是寻径，从我们蹒跚学步起，我们每天都在从A走到B。如何在游戏中实现寻径是游戏设计师每天都在思考的问题，并且，寻径是游戏兴起的数十年来，已经反复出现又反复解决的问题。'
//        },{
//          type:'empty',
//          data:''
//        },
//        {
//          type:'pic',
//          data:'请上传图片',
//          uploader:$fileUploader.create({
//            scope: $scope,
//            url: '/upload',
//            autoUpload:true
//          })
//        },
//        {
//          type:'pic-desc',
//          data:'图1：摩托车的图片'
//        }
      ]
    };
      $scope.delete = function(index){
        if(confirm('确定要删除该元素吗？删除后不可恢复！')){
          report.content.splice(index,1);
        }
      }
      $scope.insert = function(type,index){
        report.content.splice(index,0,{type:type,data:"请修改"});
      }
      $scope.readFile =function (input){
        var index = $(input).data('index');
        var file = input.files[0];
        if(!/image\/\w+/.test(file.type)){
          alert("请确保文件为图像类型");
          return false;
        }
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function(e){
          var that = this;
          $scope.$apply(function(){
            $scope.report.content[index].data = that.result;
          });

        }
      }
      $scope.bindUploader = function(scope){
        var index = scope.$parent.$index;
        var uploader;
        if(!report.content[index].uploader){
          uploader = report.content[index].uploader = $fileUploader.create({
            scope: scope,
            url: '/upload',
            autoUpload:true
          });
          uploader.filters.push(function(item /*{File|HTMLInputElement}*/) {
            var type = uploader.isHTML5 ? item.type : '/' + item.value.slice(item.value.lastIndexOf('.') + 1);
            type = '|' + type.toLowerCase().slice(type.lastIndexOf('/') + 1) + '|';
            return '|jpg|png|jpeg|bmp|'.indexOf(type) !== -1;
          });
        }

        if(uploader){
          uploader.bind('success', function (event, xhr, item, response) {
            console.info('Success', xhr, item, response);
            console.info('Success',index);
            report.content[index].data = response.name;
          });
        }

      }
      $scope.build = function(){
        var result = {};
        result.title = report.title;
        result.date = report.date;
        result.content = [];
        report.content.forEach(function(e,i){
          result.content.push({type: e.type, data: e.data});
        });
        $.ajax({
          type: 'POST'
          // , url: /\?dev/.test(window.location) ? 'http://localhost:3000' : 'http://bootstrap.herokuapp.com'
          , url: '/build'
          , dataType: 'jsonpi'
          , params: {report:result}
        });
      }
  }]);